Format CMake files

The built-in Qt Creator formatter indents the body of if, foreach and the other blocks, as well as the arguments of a call, puts one space between them and none around the parentheses, and removes whitespace from the end of the lines. Only the whitespace between the elements of a file ever changes, so its comments and strings and the line breaks you made stay as they are.

The code style determines the layout to use. The built-in Qt style is one such choice rather than a description of the file you have. Expect a file written using another layout to come back rewritten throughout: one that spells if (NOT WIN32) comes back spelling it if(NOT WIN32), until you turn on the space between a control keyword and its parenthesis.

You can also use the cmake-format tool and local .cmake-format, .py, or .json configuration files to format any text in CMake files that you do not guard with a pair of fences. You must install the tool and tell Qt Creator where you installed it.

Format current file

To format the file you are editing, go to Tools and select CMakeFormatter > Format Current File.

To change what the built-in formatter and the indentation of the CMake editor do, select Preferences > CMake > Code Style. It holds the indentation width and the tab policy, whether a space stands between the name of a command and its opening parenthesis, whether the values below a keyword of its own take a level of their own, and whether a comment at the end of a line keeps the column it is in. As with the other languages, you can copy the built-in Qt style, change the copy, and give a project a style of its own.

Format file when saving it

To pick a formatter and to format CMake files upon file save:

  1. Select Preferences > CMake > Formatter.

    Formatter tab in CMake preferences

  2. Select Built-in to use the formatter of Qt Creator, or CMakeFormat to hand the files to cmake-format.
  3. In CMakeFormat command, enter the path to cmake-format.exe.
  4. Select Automatic formatting on file save to automatically format CMake files when you save them.

    To temporarily disable this setting while saving a file, go to File and select Save Without Formatting.

  5. In Restrict to MIME types, add the MIME types of the files to format, separated by semicolons. The default value, text/x-cmake formats CMake files. If the field is empty, all files are formatted.
  6. Select Restrict to files contained in the current project to only format CMake files that belong to the current project.

See also Specify code style, How to: Build with CMake, Edit MIME types, and CMake.